﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Security.Cryptography;

namespace DiasEngineDate
{
    class Encryption_Decryption
    {
        //加密和解密|主要征对密码字段！|
        public Encryption_Decryption()
        {
            //构造函数内容
        }

        #region AES加密
        public static string Encrypt(string toEncrypt)
        {
            if (toEncrypt == "")
            {
                return "";
            }
            byte[] keyArray = UTF8Encoding.UTF8.GetBytes("12345678901234567890123456789012");
            byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);

            RijndaelManaged rDel = new RijndaelManaged();//引用命名空间的using System。SecurityCryptography;
            rDel.Key = keyArray;
            rDel.Mode = CipherMode.ECB;////引用命名空间的using System。SecurityCryptography;
            rDel.Padding = PaddingMode.PKCS7;//引用命名空间的using System。SecurityCryptography;
            ICryptoTransform cTransform = rDel.CreateEncryptor();//
            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            return Convert.ToBase64String(resultArray, 0, resultArray.Length);
        }
        #endregion AES加密


        #region AES解密
        public static string Decrypt(string toDecrypt)
        {
            if (toDecrypt == "")
            {
                return "";
            }
            try
            {
                byte[] keyArray = UTF8Encoding.UTF8.GetBytes("12345678901234567890123456789012");
                byte[] toEncryptArray = Convert.FromBase64String(toDecrypt);

                RijndaelManaged rDel = new RijndaelManaged();
                rDel.Key = keyArray;
                rDel.Mode = CipherMode.ECB;
                rDel.Padding = PaddingMode.PKCS7;

                ICryptoTransform cTransform = rDel.CreateDecryptor();
                byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

                return UTF8Encoding.UTF8.GetString(resultArray);
            }
            catch (Exception)
            {
                MessageBox.Show("解密失败", "密码算法不是本软件生成的加密算法？对明文无效？");
                return "未知算法,无法为您解密,请尝试其他算法，本解密算法只使用于本软件程式内部加密.除未知算法外。如果您输入明文用于解密，无法为明文解密，因为明文不存在任何加密算法。";
            }

        }
        #endregion AES解密
    }
}
